#pragma once
#include <iostream>
#include <string>
#include <unordered_map>
#include "Init.hpp"

#include "Log.hpp"
using std::cout;
using std::cin;
using std::endl;
Init init;

class Task
{
private:
    int _newsocket;
    const std::string _client_ip;
    const uint16_t _client_port;
    Log log;

public:
    Task(int newsocket, const std::string& client_ip, const uint16_t& client_port)
        :_newsocket(newsocket)
        ,_client_ip(client_ip)
        ,_client_port(client_port)   
    {}

    ~Task(){}
    
    //处理任务
    void run()
    {
        char buffer[4096];
        //读取客户端信息
        ssize_t n = read(_newsocket, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n-2] = 0;//telnet输入可能带/r/n去掉着两个字符
            cout << "client key: "<< buffer << endl;
            std::string message = init.Translation(buffer);
            write(_newsocket, message.c_str(), message.size());
        }
        //客户端退出
        else if(n == 0)
        {
            log(Info, "%s : %d quit, server close sockfd: %d", _client_ip.c_str(), _client_port, _newsocket);
        }
        //出错
        else
        {
            log(Info, "read error");
        }

        //处理完任务就关闭连接
        close(_newsocket);
    }

    void operator()()
    {
        run();
    }
};


